package com.coder.algorithm.offer_2;

import java.util.Locale;

/**
 * 数值的整数次方
 *
 * @author yuhushuan
 * @date 2020/6/13 11:55
 */
public class _16_1_Power {

    public static void main(String[] args) {
        // 把底数和指数分别设为正数、负数和零
        print(2.2, 3);
        print(2.2, -3);
        print(2.2, 0);

        print(-2.2, 3);
        print(-2.2, -3);
        print(-2.2, 0);

        print(0, 3);
        print(0, -3);
        print(0, 0);
    }

    private static void print(double base, int exponent) {
        System.out.println(String.format(Locale.getDefault(), "底数为 %f，指数为 %d 的值为 %f",
                base, exponent, power(base, exponent)));

    }

    private static double power(double base, int exponent) {
        if (base == 0.0 && exponent == 0) {
            return 0.0;
        }
        int absExponent = exponent;
        if (exponent < 0) {
            absExponent = -exponent;
        }
        double result = powerWithUnsignedExponent(base, absExponent);
        if (exponent < 0) {
            result = 1.0 / result;
        }
        return result;
    }

    private static double powerWithUnsignedExponent(double base, int exponent) {
        double result = 1.0;
        for (int i = 1; i <= exponent; ++i) {
            result *= base;
        }
        return result;
    }
}
